//
//  KKShareManager.m
//  KKShareManger
//
//  Created by liaozhenming on 16/3/30.
//  Copyright © 2016年 liaozhenming. All rights reserved.
//

#import "KKShareManager.h"

#import "WXApi.h"
#import "WeiboSDK.h"
#import <TencentOpenAPI/QQApiInterface.h>
#import <TencentOpenAPI/TencentOAuth.h>

static NSString* KKShareItemSina = @"com.sina.weibo";
static NSString* KKShareItemWeiXinFriends = @"ZMShareModelItemWeiXinFriends";
static NSString* KKShareItemWeiXinMessage = @"ZMShareModelItemWeiXinMessage";
static NSString* KKShareItemWeiXinFavorite = @"ZMShareModelItemWeiXinFavorite";
static NSString* KKShareItemTencent = @"com.tencent.mqq";
static NSString* KKShareItemQZone = @"com.tencent.QZone";

static UIImage* KKScaleImage(UIImage *image, CGSize scaleSize) {
    UIGraphicsBeginImageContext(scaleSize);
    [image drawInRect:CGRectMake(0, 0, scaleSize.width, scaleSize.height)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return scaledImage;
}

#pragma mark - KKShareItem methods

@interface KKShareItem : NSObject

@property (nonatomic, copy) NSString* identifier;
@property (nonatomic, copy) NSString* appkey;
@property (nonatomic, copy) NSString* appsecret;
@property (nonatomic, copy) NSString* redirectURI;

@property (nonatomic, copy) NSString* itemIcon;
@property (nonatomic, copy) NSString* itemName;

@end

@implementation KKShareItem

- (instancetype)initWithIdentifier:(NSString*)identifier appKey:(NSString*)appkey appsecret:(NSString*)appsecret redirectURI:(NSString*)redirectURI itemIcon:(NSString*)itemIcon itemName:(NSString*)itemName {
    self = [super init];
    if (self) {
        _identifier = identifier;
        _appkey = appkey;
        _appsecret = appsecret;
        _redirectURI = redirectURI;
        _itemIcon = itemIcon;
        _itemName = itemName;
    }
    return self;
}
@end

#pragma mark - KKSharePannelView methods

typedef void(^KKSharePannelViewSelectedIndexBlock)(KKShareItem* shareItem);

@interface KKSharePannelView : UIView

@property (nonatomic, strong) UIView *functionView;
@property (nonatomic, strong) UIView *shareItemsBackgroundView;
@property (nonatomic, strong) UIScrollView *shareItemsView;
@property (nonatomic, strong) UIButton *cancelButton;

@property (nonatomic, copy) KKSharePannelViewSelectedIndexBlock selectedIndexHandle;

- (instancetype)initWithShareManager:(KKShareManager*)shareManager;

- (void)appear;

- (void)disAppear;

@end

@interface KKShareAlertView : KKSharePannelView

@end

#pragma mark - KKShareReslutItem methodsd

@interface KKShareResultModel : NSObject <WXApiDelegate, WeiboSDKDelegate, QQApiInterfaceDelegate>

@end

@implementation KKShareResultModel

#pragma mark - Delegate methods

- (void)onResp:(BaseResp*)resp {
    NSString* alertMessage = nil;
    if ([resp isKindOfClass: [SendMessageToWXResp class]]) {
        
        NSInteger errorCode = resp.errCode;
        
        if (errorCode == 0) {
            alertMessage = @"分享成功";
        }
        else if (errorCode == -2) {
            alertMessage = @"取消分享";
        }
        else {
            alertMessage = @"分享失败";
        }
        
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle: @"微信分享" message: alertMessage delegate: nil cancelButtonTitle: nil otherButtonTitles: @"关闭", nil];
        [alertView show];
    }
    else if([resp isKindOfClass: [SendMessageToQQResp class]]){
        
        SendMessageToQQResp* sendResp = (SendMessageToQQResp*)resp;
        
        if (sendResp.type == ESENDMESSAGETOQQRESPTYPE) {
            
            NSString* resultCode = sendResp.result;
            if ([resultCode isEqualToString: @"0"]) {
                alertMessage = @"分享成功";
            }
            else if ([resultCode isEqualToString: @"-4"]) {
                alertMessage = @"取消分享";
            }
            else {
                alertMessage = @"分享失败";
            }
            
            UIAlertView* alertView = [[UIAlertView alloc] initWithTitle: @"QQ分享" message: alertMessage delegate: nil cancelButtonTitle: nil otherButtonTitles: @"关闭", nil];
            [alertView show];
        }
    }
}

#pragma mark -
#pragma mark - WeiboSDKDelegate methods

- (void)didReceiveWeiboRequest:(WBBaseRequest *)request {
    
    //  do nothing
}

- (void)didReceiveWeiboResponse:(WBBaseResponse *)response {
    
    if ([response isKindOfClass: [WBSendMessageToWeiboResponse class]]) {
        
        NSInteger statusCode = response.statusCode;
        NSString* alertMessage = @"";
        
        if (statusCode == 0) {
            alertMessage = @"分享成功";
        }
        else if (statusCode == -1) {
            alertMessage = @"取消分享";
        }
        else {
            alertMessage = @"分享失败";
        }
        
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle: @"微博分享" message: alertMessage delegate: nil cancelButtonTitle: nil otherButtonTitles: @"关闭", nil];
        [alertView show];
    }
}

#pragma mark -
#pragma mark - QQApiInterfaceDelegate methods

- (void)onReq:(QQBaseReq *)req {
    
    // do nothing
}

- (void)isOnlineResponse:(NSDictionary *)response {
    
    NSLog(@"response = %@", response);
}

@end


#pragma mark - KKShareManager methods

@interface KKShareManager()

@property (nonatomic, strong) NSMutableArray *kk_platformItems;

@property (nonatomic, strong) NSString *shareTitle;
@property (nonatomic, strong) NSString *shareDescription;
@property (nonatomic, strong) UIImage *shareImage;
@property (nonatomic, strong) NSString *shareWebURL;

@property (nonatomic, strong) KKSharePannelView *sharePannelView;
@property (nonatomic, strong) KKShareResultModel *shareResultModel;

@end

@implementation KKShareManager

+ (instancetype)shareManager {
    static KKShareManager *shareManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareManager = [KKShareManager new];
    });
    return shareManager;
}

- (void)addSharePlatformItem:(KKShareItem*)item {
    
    if (_kk_platformItems == nil) {
        _kk_platformItems = [NSMutableArray array];
    }
    
    for (KKShareItem *ownItem in _kk_platformItems) {
        if ([ownItem.identifier isEqualToString: item.identifier]) {
            return;
        }
    }
    [_kk_platformItems addObject: item];
}

- (void)shareContentWithPlatformItem:(KKShareItem*)item {
    
    if ([item.identifier isEqualToString: KKShareItemSina]) {
        //  新浪
        WBMessageObject *message = [WBMessageObject message];
        
        NSString* content = @"";
        if (_shareTitle) {
            content = [NSString stringWithFormat: @"【%@】\n", _shareTitle];
        }
        if (_shareDescription) {
            content = [content stringByAppendingString: _shareDescription];
        }
        if (_shareWebURL) {
            content = [content stringByAppendingString: [NSString stringWithFormat: @"  \n%@\n", _shareWebURL]];
        }
        message.text = content;
        
        if (_shareImage) {
            WBImageObject *image = [WBImageObject object];
            image.imageData = UIImageJPEGRepresentation(_shareImage, 0.8);
            message.imageObject = image;
        }
        
        WBAuthorizeRequest *authRequest = [WBAuthorizeRequest request];
        authRequest.redirectURI = item.redirectURI;
        authRequest.scope = @"all";
        
        WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage: message authInfo:authRequest access_token: nil];
        BOOL successful = [WeiboSDK sendRequest:request];
        if (!successful) {
            NSLog(@"分享失败");
        }
        return;
    }
    if ([item.identifier isEqualToString: KKShareItemTencent]) {
        //腾讯
        QQApiNewsObject* img = [QQApiNewsObject objectWithURL: [NSURL URLWithString: _shareWebURL] title: _shareTitle description: _shareDescription previewImageData: _shareImage ? UIImageJPEGRepresentation(_shareImage, 0.8) : nil];
        SendMessageToQQReq* reqquest = [SendMessageToQQReq reqWithContent: img];
        [QQApiInterface sendReq: reqquest];
        
        return;
    }
    if ([item.identifier isEqualToString: KKShareItemQZone]) {
        
        //QQ空间
        QQApiNewsObject* img = [QQApiNewsObject objectWithURL: [NSURL URLWithString: _shareWebURL] title: _shareTitle description: _shareDescription previewImageData: _shareImage ? UIImageJPEGRepresentation(_shareImage, 0.8) : nil];
        SendMessageToQQReq* reqquest = [SendMessageToQQReq reqWithContent: img];
        [QQApiInterface SendReqToQZone: reqquest];
        return;
    }
    if ([item.identifier isEqualToString: KKShareItemWeiXinFriends] || [item.identifier isEqualToString: KKShareItemWeiXinFavorite] || [item.identifier isEqualToString: KKShareItemWeiXinMessage]) {
        
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = _shareTitle;
        message.description = _shareDescription;
        
        NSData *imageData = UIImageJPEGRepresentation(_shareImage,1.0);
    
        if (imageData.length > 32 * 1024.0) {
            UIImage *scaleImage = KKScaleImage(_shareImage, CGSizeMake(100, 100));
            imageData = UIImageJPEGRepresentation(scaleImage, 1.0);
        }
        [message setThumbData: imageData];
        
        WXWebpageObject *ext = [WXWebpageObject object];
        ext.webpageUrl = _shareWebURL;
        
        message.mediaObject = ext;
        
        SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
        req.bText = NO;
        req.message = message;
        
        if ([item.identifier isEqualToString: KKShareItemWeiXinFavorite]) {
            req.scene = WXSceneFavorite;
        }
        if ([item.identifier isEqualToString: KKShareItemWeiXinMessage]) {
            req.scene = WXSceneTimeline;
        }
        if ([item.identifier isEqualToString: KKShareItemWeiXinFriends]) {
            req.scene = WXSceneSession;
        }
        [WXApi sendReq:req];
    }
}

#pragma mark - Public methods

+ (void)registerSinaWithAppKey:(NSString *)appkey appSecret:(NSString*)appSecret {
    [self registerSinaWithAppKey: appkey appSecret: appSecret appRequired: NO];
}

+ (void)registerSinaWithAppKey:(NSString *)appkey appSecret:(NSString*)appSecret appRequired:(BOOL)required {
    [KKShareManager shareManager];
    BOOL isRegister = [WeiboSDK registerApp: appkey];
    if (isRegister) {
        
        KKShareItem* shareItem = [KKShareItem new];
        shareItem.identifier = KKShareItemSina;
        shareItem.appkey = [appkey copy];
        shareItem.appsecret = [appSecret copy];
        
        shareItem.itemIcon = @"weibo";
        shareItem.itemName = @"微博";
        
        [[KKShareManager shareManager] addSharePlatformItem: shareItem];
    }
}

+ (void)registerWeiXinWithAppKey:(NSString *)appkey appSecret:(NSString*)appSecret {
    return[self registerWeiXinWithAppKey: appkey appSecret:appSecret appRequired: YES];
}

+ (void)registerWeiXinWithAppKey:(NSString *)appkey appSecret:(NSString*)appSecret appRequired:(BOOL)required {
    
    BOOL result = YES;
    
    if (required) {
        result = [WXApi isWXAppInstalled] || [WXApi isWXAppSupportApi];
    }
    
    if (result) {
        BOOL isRegister = [WXApi registerApp: appkey];
        if (isRegister) {
            
            KKShareItem* friendsItem = [KKShareItem new];
            friendsItem.identifier = KKShareItemWeiXinFriends;
            friendsItem.appkey = [appkey copy];
            friendsItem.appsecret = [appSecret copy];
            friendsItem.redirectURI = nil;
            friendsItem.itemIcon = @"weixin";
            friendsItem.itemName = @"微信好友";
            
            [[KKShareManager shareManager] addSharePlatformItem: friendsItem];
            
            KKShareItem* messageItem = [KKShareItem new];
            messageItem.identifier = KKShareItemWeiXinMessage;
            messageItem.appkey = [appkey copy];
            messageItem.appsecret = [appSecret copy];
            messageItem.redirectURI = nil;
            messageItem.itemIcon = @"quan";
            messageItem.itemName = @"微信朋友圈";
            
            [[KKShareManager shareManager] addSharePlatformItem: messageItem];
            
            //            KKShareItem* favoriteItem = [KKShareItem new];
            //            favoriteItem.identifier = KKShareItemWeiXinFavorite;
            //            favoriteItem.appkey = [appkey copy];
            //            favoriteItem.appsecret = [appSecret copy];
            //            favoriteItem.redirectURI = nil;
            //            favoriteItem.itemIcon = @"sns_icon_4";
            //            favoriteItem.itemName = @"微信收藏";
            
            //            [[KKShareManager shareManager] addSharePlatformItem: favoriteItem];
        }
    }
}

+ (void)registerQQWithAppKey:(NSString *)appkey appSecret:(NSString*)appSecret {
    return[self registerQQWithAppKey: appkey appSecret:appSecret appRequired: YES];
}

+ (void)registerQQWithAppKey:(NSString *)appkey appSecret:(NSString*)appSecret appRequired:(BOOL)required {
    BOOL result = YES;
    if (required) {
        result = [QQApiInterface isQQInstalled] || [QQApiInterface isQQSupportApi];
    }
    
    if (result) {
        TencentOAuth* oAuth = [[TencentOAuth alloc] initWithAppId: appkey andDelegate: nil];
        if (oAuth) {
            KKShareItem* qqItem = [KKShareItem new];
            qqItem.identifier = KKShareItemTencent;
            qqItem.appkey = [appkey copy];
            qqItem.itemIcon = @"qq";
            qqItem.itemName = @"QQ好友";
            
            [[KKShareManager shareManager] addSharePlatformItem: qqItem];
            
            KKShareItem* QZoneItem = [KKShareItem new];
            QZoneItem.identifier = KKShareItemQZone;
            QZoneItem.appkey = [appkey copy];
            QZoneItem.itemIcon = @"kongjian";
            QZoneItem.itemName = @"QQ空间";
            
            [[KKShareManager shareManager] addSharePlatformItem: QZoneItem];
        }
    }
}

+ (BOOL)shareResultHandleOpenURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    
    KKShareManager *shareManager = [KKShareManager shareManager];
    shareManager.shareResultModel = [KKShareResultModel new];
    
    if ([sourceApplication isEqualToString: KKShareItemSina]) {
        return  [WeiboSDK handleOpenURL:url delegate: shareManager.shareResultModel];
    }
    else if([sourceApplication isEqualToString: KKShareItemTencent]) {
        return [QQApiInterface handleOpenURL: url delegate: shareManager.shareResultModel];
    }
    else if ([sourceApplication isEqualToString: @"com.tencent.xin"]) {
        return  [WXApi handleOpenURL:url delegate: shareManager.shareResultModel];
    }
    
    return YES;
}

#pragma mark - 分享内容
+ (void)shareContentWithTitle:(NSString*)title description:(NSString*)description image:(id)image webURL:(NSString*)webURL {
    
    KKShareManager *shareManager = [KKShareManager shareManager];
    
    [shareManager setShareTitle: title];
    [shareManager setShareDescription: description];
    [shareManager setShareWebURL: webURL];
    
    if ([image isKindOfClass: [UIImage class]]) {
        [[KKShareManager shareManager] setShareImage: image];
    }
    else if ([image isKindOfClass: [NSString class]]) {
        NSString *imageString = (NSString*)image;
        if ([imageString hasPrefix: @"http://"] || [imageString hasPrefix: @"https://"]) {
            //  图片资源为网络资源
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                NSData* imageData = [NSData dataWithContentsOfURL: [NSURL URLWithString: image]];
                [[KKShareManager shareManager] setShareImage: [UIImage imageWithData: imageData]];
            });
        }
        else if([imageString rangeOfString: @"/"].location > 0 && [imageString rangeOfString: @"/"].location < imageString.length){
            //  图片资源为文件路径
            [[KKShareManager shareManager] setShareImage: [UIImage imageWithContentsOfFile: image]];
        }
        else {
            //  图片资源为imageName
            [[KKShareManager shareManager] setShareImage: [UIImage imageNamed: image]];
        }
    }
    
    //  执行弹出框的操作
    
    KKSharePannelView *pannelView = shareManager.sharePannelView;
    
    if (pannelView == nil) {
        __weak typeof(shareManager) weakManager = shareManager;
        pannelView = [[KKShareAlertView alloc] initWithShareManager: shareManager];
        pannelView.selectedIndexHandle = ^(KKShareItem *item){
            [weakManager shareContentWithPlatformItem: item];
        };
        shareManager.sharePannelView = pannelView;
    }
    [pannelView appear];
}

@end


#pragma mark - KKSharePannelView methods
@implementation KKSharePannelView

- (instancetype)initWithShareManager:(KKShareManager*)shareManager {
    CGFloat width = CGRectGetWidth([[UIScreen mainScreen] bounds]);
    
    self = [super initWithFrame: CGRectMake(0, 0, width, CGRectGetHeight([[UIScreen mainScreen] bounds]))];
    if (self) {
        
        NSInteger itemCount = [shareManager kk_platformItems].count;
        
        _functionView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, width, itemCount < 4 ? 210 : 320)];
        [self addSubview: _functionView];
        
        _shareItemsBackgroundView = [[UIView alloc] initWithFrame: CGRectMake(10, 10, width - 20, CGRectGetHeight(_functionView.bounds) - 70)];
        
        _shareItemsBackgroundView.backgroundColor = [UIColor whiteColor];
        _shareItemsBackgroundView.layer.cornerRadius = 20.0f;
        
        _shareItemsView = [[UIScrollView alloc] initWithFrame: CGRectMake(10, 10, CGRectGetWidth(_shareItemsBackgroundView.bounds) - 20, CGRectGetHeight(_shareItemsBackgroundView.bounds) - 20)];
        _shareItemsView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        _shareItemsView.backgroundColor = [UIColor clearColor];
        _shareItemsView.pagingEnabled = YES;
        [_shareItemsBackgroundView addSubview: _shareItemsView];
        [_functionView addSubview: _shareItemsBackgroundView];
        
        _cancelButton = [UIButton buttonWithType: UIButtonTypeCustom];
        _cancelButton.frame = CGRectMake(15, CGRectGetHeight(_functionView.bounds) - 50, width - 30, 40);
        _cancelButton.backgroundColor = [UIColor whiteColor];
        [_cancelButton setTitle: @"取消" forState: UIControlStateNormal];
        [_cancelButton setTitleColor: [UIColor colorWithRed: 0 green:122.0/255.0 blue: 1.0 alpha: 1.0] forState: UIControlStateNormal];
        [_cancelButton addTarget: self action: @selector(kk_onTap:) forControlEvents: UIControlEventTouchUpInside];
        _cancelButton.layer.cornerRadius = 10.0f;
        [_functionView addSubview: _cancelButton];
        
        [self updateItemsViewWithItemCount: itemCount];
    }
    return self;
}

#pragma mark - Public methods

- (void)appear {
    
    UIWindow* keywindow = [[UIApplication sharedApplication] keyWindow];
    
    CGFloat width = CGRectGetWidth(keywindow.bounds);
    CGFloat height = CGRectGetHeight(keywindow.bounds);
    
    [keywindow addSubview: self];
    
    _functionView.center = CGPointMake(width/2, height + CGRectGetHeight(_functionView.bounds)/2);
    
    __weak UIView* weakFunctionView = _functionView;
    __weak UIView* weakSelf = self;
    
    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
    [UIView animateWithDuration: 0.25 animations:^{
        
        weakSelf.backgroundColor = [UIColor colorWithWhite: 0.0 alpha: 0.3];
        
        weakFunctionView.center = CGPointMake(width/2, height - CGRectGetHeight(weakFunctionView.bounds)/2);
    }completion:^(BOOL finished) {
        [[UIApplication sharedApplication] endIgnoringInteractionEvents];
    }];
}


- (void)disAppear {
    
    UIWindow* keywindow = [[UIApplication sharedApplication] keyWindow];
    
    CGFloat width = CGRectGetWidth(keywindow.bounds);
    CGFloat height = CGRectGetHeight(keywindow.bounds);
    
    __weak UIView* weakFunctionView = _functionView;
    __weak UIView* weakSelf = self;
    
    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
    [UIView animateWithDuration: 0.25 animations:^{
        
        weakSelf.backgroundColor = [UIColor colorWithWhite: 0.0 alpha: 0.01];
        
        weakFunctionView.center = CGPointMake(width/2, height + CGRectGetHeight(weakFunctionView.bounds)/2);
    }completion:^(BOOL finished) {
        [[UIApplication sharedApplication] endIgnoringInteractionEvents];
        [weakSelf removeFromSuperview];
    }];
}

#pragma mark - Private methods

- (void)updateItemsViewWithItemCount:(NSInteger)itemCount {
    
    
    CGFloat itemScrollViewWidth = CGRectGetWidth(_shareItemsView.bounds);
    CGFloat itemScrollViewHeight = CGRectGetHeight(_shareItemsView.bounds);
    
    CGFloat itemViewWidth = 60;
    CGFloat itemViewHeight = 80;
    
    CGFloat itemViewOffsetX;
    
    NSInteger numberLine = itemCount / 3 > 0 ? 2 : 1;
    if (numberLine == 2) {
        itemViewOffsetX = (itemScrollViewWidth - itemViewWidth * 3) / 4;
    }
    else {
        itemViewOffsetX = (itemScrollViewWidth - itemViewWidth * itemCount) / (itemCount + 1);
    }
    
    CGFloat itemViewOffsetY = (itemScrollViewHeight - itemViewHeight * numberLine) / (numberLine + 1);
    
    for (NSInteger index = 0; index < itemCount; index++) {
        
        NSInteger pageIndex = index / 6;
        
        NSInteger coverIndex = index - (pageIndex * 6);
        NSInteger coverLine = coverIndex / 3;
        
        CGFloat pointX = itemViewOffsetX * (coverIndex % 3 + 1) + itemViewWidth * (coverIndex % 3) + itemScrollViewWidth * pageIndex;
        CGFloat pointY = itemViewOffsetY * (coverLine + 1) + itemViewHeight * coverLine;
        
        UIButton* itemButton = [UIButton buttonWithType: UIButtonTypeCustom];
        itemButton.frame = CGRectMake(pointX, pointY, itemViewWidth, itemViewHeight);
        itemButton.titleLabel.adjustsFontSizeToFitWidth = YES;
        
        KKShareItem* shareItem = [[KKShareManager shareManager].kk_platformItems objectAtIndex: index];
        
        UIImage* image = [UIImage imageNamed: shareItem.itemIcon];
        NSString* name = shareItem.itemName;
        
        itemButton.titleLabel.font = [UIFont systemFontOfSize: 12];
        [itemButton setImage: image forState: UIControlStateNormal];
        [itemButton setImageEdgeInsets: UIEdgeInsetsMake(-20, 1, 0, 0)];
        [itemButton setTitle: name forState: UIControlStateNormal];
        [itemButton setTitleColor: [UIColor blackColor] forState: UIControlStateNormal];
        [itemButton setTitleEdgeInsets: UIEdgeInsetsMake(60, -59, 0, 0)];
        [itemButton addTarget: self action: @selector(kk_choosed:) forControlEvents: UIControlEventTouchUpInside];
        itemButton.tag = index;
        [_shareItemsView addSubview: itemButton];
    }
    
    NSInteger page = itemCount % 6 == 0 ? itemCount / 6 : itemCount / 6 + 1;
    _shareItemsView.contentSize = CGSizeMake(itemScrollViewWidth * page,  itemScrollViewHeight);
}

#pragma mark - Action methods

- (void)kk_onTap:(UIButton*)sender {
    
    [self disAppear];
}

- (void)kk_choosed:(UIButton*)sender {
    
    if (self.selectedIndexHandle) {
        NSInteger index = sender.tag;
        KKShareItem* shareItem = [[KKShareManager shareManager].kk_platformItems objectAtIndex: index];
        self.selectedIndexHandle(shareItem);
    }
    
    [self disAppear];
}

@end

@implementation KKShareAlertView

- (instancetype)initWithShareManager:(KKShareManager *)shareManager {
    
    CGFloat width = CGRectGetWidth([[UIScreen mainScreen] bounds]);
    CGFloat height = CGRectGetHeight([[UIScreen mainScreen] bounds]);
    
    self = [super initWithFrame: CGRectMake(0, 0, width, height)];
    if (self) {
        
        NSInteger itemCount = [shareManager kk_platformItems].count;
        
        CGFloat functionViewWidth = 250;
        CGFloat functionViewHeight = 282;
        
        CGFloat itemWidth = functionViewWidth/ 3.0;
        
        if (itemCount < 4) {
            functionViewHeight -= itemWidth;
        }
        
        self.functionView = [[UIView alloc] initWithFrame: CGRectMake((width - 250)/2, 0, functionViewWidth,functionViewHeight)];
        self.functionView.backgroundColor = [UIColor whiteColor];
        self.functionView.center = CGPointMake(width/2, height/2);
        [self addSubview: self.functionView];
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame: CGRectMake(0, 10, CGRectGetWidth(self.functionView.bounds), 20)];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.text = @"分享给小伙伴";
        titleLabel.font = [UIFont systemFontOfSize: 15];
        [self.functionView addSubview: titleLabel];
        
        for (NSInteger index = 0; index < itemCount; index++) {
            
            UIButton* itemButton = [UIButton buttonWithType: UIButtonTypeCustom];
            itemButton.titleLabel.adjustsFontSizeToFitWidth = YES;
            
            KKShareItem* shareItem = [[KKShareManager shareManager].kk_platformItems objectAtIndex: index];
            
            UIImage* image = [UIImage imageNamed: shareItem.itemIcon];
            NSString* name = shareItem.itemName;
            
            itemButton.titleLabel.font = [UIFont systemFontOfSize: 12];
            [itemButton setImage: image forState: UIControlStateNormal];
            [itemButton setImageEdgeInsets: UIEdgeInsetsMake(-10, 13, 0, 0)];
            [itemButton setTitle: name forState: UIControlStateNormal];
            [itemButton setTitleColor: [UIColor darkGrayColor] forState: UIControlStateNormal];
            [itemButton setTitleEdgeInsets: UIEdgeInsetsMake(60, -45, 0, 0)];
            [itemButton addTarget: self action: @selector(kk_choosed:) forControlEvents: UIControlEventTouchUpInside];
            itemButton.tag = index;
            [self.functionView addSubview: itemButton];
            
            if (index < 3) {
                
                itemButton.frame = CGRectMake(itemWidth * index, 50, itemWidth, itemWidth);
            }
            else {
                itemButton.frame = CGRectMake(itemWidth * (index % 3) + itemWidth/2, 50 + itemWidth, itemWidth, itemWidth);
            }
        }
        
        
        UIButton *cancelButton = [UIButton buttonWithType: UIButtonTypeCustom];
        cancelButton.frame = CGRectMake((CGRectGetWidth(self.functionView.bounds) - 30)/2, CGRectGetHeight(self.functionView.bounds) - 55, 30, 30);
        [cancelButton setImage: [UIImage imageNamed: @"close"] forState: UIControlStateNormal];
        [cancelButton addTarget: self action: @selector(kk_onTap:) forControlEvents: UIControlEventTouchUpInside];
        [self.functionView addSubview: cancelButton];
        
    }
    return self;
}

- (void)appear {
    
    UIWindow* keywindow = [[UIApplication sharedApplication] keyWindow];
    [keywindow addSubview: self];
    
    self.functionView.transform = CGAffineTransformMakeScale(CGFLOAT_MIN, CGFLOAT_MIN);
    
    __weak UIView* weakFunctionView = self.functionView;
    __weak UIView* weakSelf = self;
    
    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
    [UIView animateWithDuration: 0.25 animations:^{
        
        weakSelf.backgroundColor = [UIColor colorWithWhite: 0.0 alpha: 0.5];
        weakFunctionView.transform = CGAffineTransformIdentity;
    }completion:^(BOOL finished) {
        [[UIApplication sharedApplication] endIgnoringInteractionEvents];
    }];
}


- (void)disAppear {
    
    __weak UIView* weakFunctionView = self.functionView;
    __weak UIView* weakSelf = self;
    
    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
    [UIView animateWithDuration: 0.25 animations:^{
        
        weakFunctionView.transform = CGAffineTransformMakeScale(0.001, 0.001);
        weakSelf.backgroundColor = [UIColor colorWithWhite: 0.0 alpha: 0.001];
    }completion:^(BOOL finished) {
        [[UIApplication sharedApplication] endIgnoringInteractionEvents];
        [weakSelf removeFromSuperview];
    }];
}

@end
